import JMessage from './jmessage-sdk-web.2.6.0.min'
import md5 from 'md5'

const appkey = '47ef9dd891349722c2c6866d';//开发者在极光平台注册的 IM 应用 appkey
const appSecret = 'b2051b9498b42af90acd0dc4';//开发者在极光平台注册的 IM 应用 masterSecret
const random_str = '295aeefc4783502a3fa3c83a467c24d2'; //20-36长度的随机字符串, 作为签名加 salt 使用
export default class Index {
    constructor() {
        this.JIM = new JMessage({debug: true})
        this.JIM.onDisconnect((data) => {
            console.log('断开连接--->', data)
        });
    }

    /**
     * 初始化
     */
    init() {
        if (!this.JIM.isInit()) {
            let timestamp = Date.now();
            let signature = md5(`appkey=${appkey}&timestamp=${timestamp}&random_str=${random_str}&key=${appSecret}`);
            this.JIM.init({
                appkey,
                random_str,
                signature,
                timestamp,
                flag: 0//	是否启用消息记录漫游，默认 0 否，1 是
            }).onSuccess(() => {
                console.log('初始化成功-->')
            }).onFail(data => {
                console.log('初始化失败-->', data)
            });
        }
    }

    /**
     * 登录
     */
    login(username, password, onSucc, onFail) {

        if (!this.JIM.isLogin()) {
            console.log('开始登录--->')
            this.JIM.login({username, password})
                .onSuccess(() => {
                    window.localStorage.setItem('username', username);
                    window.localStorage.setItem('password', password);
                    onSucc();
                })
                .onFail(data => {
                    if (data.code === 880103) {//未注册
                        console.log('未注册，开始注册--->')
                        this.JIM.register({username, password})
                            .onSuccess(msg => {
                                console.log('注册成功--->', msg)
                                this.login(username, password)
                            }).onFail(onFail);
                    } else {
                        console.log('登录失败--->', data)
                        onFail(data)
                    }
                });
        }
    }

    /**
     * 登出
     */
    loginOut() {
        window.localStorage.clear();
        this.JIM.loginOut()
        if (!this.JIM.isLogin()) {
            console.log('成功登出--->')
        }
    }

    isLogin() {
        let username = window.localStorage.getItem('username');
        let password = window.localStorage.getItem('password');
        return username && password && this.JIM.isLogin();
    }

    /**
     * 获取个人信息
     */
    getUserInfo(onSucc) {
        if (!this.isLogin()) {
            return;
        }
        let username = window.localStorage.getItem('username');
        this.JIM.getUserInfo({
            username,
            appkey
        }).onSuccess(onSucc)
            .onFail((data) => {
                console.log('获取个人信息失败--->', data)
            })
    }

}
